package com.tiandang.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import tiandang.core.service.ExportService;
import tiandang.core.service.FileStore;

import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/api/export")
public class ExportController {

  @Autowired
  private ExportService exportService;

  @Autowired
  private FileStore fileStore;

  @GetMapping("/order")
  public void exportOrder(@RequestParam(value = "startTimestamp", required = false) Long startTimestamp,
                          @RequestParam(value = "endTimestamp", required = false) Long endTimestamp,
                          @RequestParam(value = "managerName", required = false) String managerName,
                          @RequestParam(value = "productName", required = false) String productName,
                          @RequestParam(value = "deliveryStatus", required = false) Integer deliveryStatus,
                          @RequestParam(value = "orderId", required = false) String orderId, HttpServletResponse response) throws Exception {

    exportService.exportOrder(startTimestamp, endTimestamp, managerName, productName, deliveryStatus,
      orderId, response);
  }


  @GetMapping("/qrcode")
  public HttpEntity<byte[]> qrcode(@RequestParam(value = "imgPath") String imgPath,
                                   @RequestParam(value = "managerName") String managerName) throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    headers.setContentDispositionFormData("attachment", new String((managerName+".jpg").getBytes("utf-8"), "ISO8859-1"));
    return new HttpEntity<byte[]>(FileUtils.readFileToByteArray(fileStore.getFileByFilePath(imgPath)), headers);
  }

}
